package com.motionlog.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.motionlog.R;
import com.motionlog.model.Base;
import com.motionlog.model.Database;

public class NewItemAddition extends Activity implements OnClickListener {

	private static final String TAG = null;
	private static final String LOG_TAG = null;
	Button method;
	ArrayList<Base> methods = new ArrayList<Base>();
	EditText description;
	TextView customMethod;
	EditText remark;

	Intent preIntent;

	// long logId;

	Database mDb;
	String summary = "";
	Button record;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_item_addition);

		mDb = Database.getInstance(this);

		description = (EditText) findViewById(R.id.description);
		customMethod = (TextView) findViewById(R.id.custom_method);
		remark = (EditText) findViewById(R.id.remark);

		Button controll = (Button) findViewById(R.id.controll);
		controll.setOnClickListener(this);
		Button uncontroll = (Button) findViewById(R.id.uncontroll);
		uncontroll.setOnClickListener(this);

		Button back = (Button) findViewById(R.id.back);
		back.setOnClickListener(this);
		Button help = (Button) findViewById(R.id.help);
		help.setOnClickListener(this);

		record = (Button) findViewById(R.id.record);
		record.setOnClickListener(this);

		method = (Button) findViewById(R.id.method);
		method.setOnClickListener(this);

		preIntent = getIntent();
		// logId = preIntent.getLongExtra("logId", -1);

		// i.putExtra("motion_id", curentMotion.id);
		// i.putExtra("level", level.getProgress());
		// i.putExtra("summary", summary);
		// i.putExtra("reasons", reasons);

	}

	private void updateDbLog() {
		int motionId = preIntent.getIntExtra("motion_id", -1);
		int level = preIntent.getIntExtra("level", -1);
		String summary = preIntent.getStringExtra("summary");
		ArrayList<Base> reasons = preIntent
				.getParcelableArrayListExtra("reasons");

		final long logId = mDb.insertLog(motionId, level, summary);
		for (Base reason : reasons) {
			mDb.insertReasonLog(logId, reason.id);
		}

		for (Base method : methods) {
			mDb.insertMethodLog(logId, method.id);
		}
		mDb.updateLog(logId, description.getText().toString(), remark.getText()
				.toString(), summary);

		mDb.updateLogFinishStep(logId, 1);

		if (mFileName != null) {
			File recordFile = new File(mFileName);
			String newPath = recordFile.getParentFile().getAbsolutePath()
					+ "/log.method.desc." + logId + ".3gp";
			android.util.Log.d(TAG, "newPath: " + newPath);
			recordFile.renameTo(new File(newPath));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.controll: {
			updateDbLog();

			Intent i = new Intent(this, ThrowEnvl.class);
			startActivity(i);
		}
			break;
		case R.id.uncontroll: {
			// updateDbLog();

			SharedPreferences settings = getSharedPreferences("settings",
					MODE_PRIVATE);
			boolean tutor = settings.getBoolean("cognitive-tutor", true);

			Class startActivity;
			if (tutor) {
				startActivity = CognitiveTherapyTutorial.class;
				settings.edit().putBoolean("cognitive-tutor", false).apply();
			} else {
				startActivity = CognitiveTherapy.class;
			}
			Intent i = new Intent(this, startActivity);
			i.putExtras(preIntent);
			i.putExtra("method-summary", summary);
			i.putExtra("methods", methods);
			i.putExtra("description", description.getText().toString());
			i.putExtra("remark", remark.getText().toString());
			i.putExtra("record-desc", mFileName);

			int motionId = i.getIntExtra("motion_id", -1);
			android.util.Log.d(TAG, "pre, motionId: " + motionId);
			// description.getText().toString(), remark.getText()
			// .toString()
			// i.putExtra("logId", logId);
			startActivity(i);
		}
			break;
		case R.id.method: {
			startActivityForResult(new Intent(NewItemAddition.this,
					SelectMethod.class), 0);
		}
			break;
		case R.id.back:
			finish();
			break;
		case R.id.help:
			//
			break;
		case R.id.record:
			if (mIsRecord) {
				stopRecording();
				record.setBackgroundResource(R.drawable.record);
			} else {
				startRecording("desc");
				record.setBackgroundResource(R.drawable.stop);
			}
			mIsRecord = !mIsRecord;
			break;
		default:
			break;
		}
	}

	MediaRecorder mRecorder;
	String mFileName = null;
	boolean mIsRecord = false;

	private void startRecording(String name) {
		mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
		mFileName += "/Android/data/com.motionlog/record";
		mFileName += "/temp." + name + ".3gp";
		android.util.Log.d(TAG, "mFileName: " + mFileName);

		File file = new File(mFileName);
		File dir = new File(file.getParent());
		if (!dir.isDirectory()) {
			if (!dir.mkdirs()) {
				android.util.Log.i(TAG,
						"mkdir failed. dir: " + file.getParent());
				return;
			}
		}
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				android.util.Log.i(TAG, "create file failed.");
				return;
			}
		}

		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			mRecorder.prepare();
		} catch (IOException e) {
			android.util.Log.e(LOG_TAG, "prepare() failed");
		}

		mRecorder.start();
	}

	private void stopRecording() {
		mRecorder.stop();
		mRecorder.release();
		mRecorder = null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			if (resultCode == RESULT_OK) {
				summary = data.getStringExtra("summary");
				methods = data.getParcelableArrayListExtra("methods");
				customMethod.setText(summary);
			}
			break;
		default:
			break;
		}
	}
}
